using UnityEngine.Experimental.Rendering;

namespace UnityEngine.Rendering.Universal
{
    public class GrabTexturePass : ScriptableRenderPass
    {
        RenderTargetIdentifier m_CameraDepthAttachment;
        ShaderTagId m_ShaderTagId;
        ProfilingSampler m_ProfilingSampler;
        FilteringSettings m_FilteringSettings;
        string m_ProfilerTag;

        private RTHandle m_Depth;
        private RTHandle m_Color;
        
        static readonly int s_DistortionUVOffsetTexture = Shader.PropertyToID("_DistortionOffsetTex");

        public GrabTexturePass(string profilerTag, RenderPassEvent evt)
        {
            m_ProfilerTag = profilerTag;
            m_ShaderTagId = new ShaderTagId("SetFXDistortionInfoPass");
            renderPassEvent = evt;
            m_ProfilingSampler = new ProfilingSampler(m_ProfilerTag);
            m_FilteringSettings = new FilteringSettings(RenderQueueRange.transparent);
        }

        public void Setup(RTHandle color,RTHandle depth)
        {
            this.m_Color = color;
            this.m_Depth = depth;
        }

        public override void Configure(CommandBuffer cmd,RenderTextureDescriptor cameraTextureDescripor){
           
            cmd.SetGlobalTexture(s_DistortionUVOffsetTexture,m_Color.nameID);
            ConfigureTarget(m_Color,m_Depth);
            ConfigureClear(ClearFlag.Color,Color.black);
            ConfigureDepthStoreAction(RenderBufferStoreAction.DontCare);
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            var cmd = renderingData.commandBuffer;
            using (new ProfilingScope(cmd, m_ProfilingSampler))
            {
                var drawSettings = CreateDrawingSettings(m_ShaderTagId, ref renderingData, SortingCriteria.CommonTransparent);
                var filterSettings = m_FilteringSettings;
                context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings);
            }
            cmd.SetGlobalTexture(s_DistortionUVOffsetTexture, m_Color.nameID);
        }
        
        //
        // public override void FrameCleanup(CommandBuffer cmd){
        //     cmd.ReleaseTemporaryRT(s_DistortionUVOffsetTexture);       
        // }
    }
}
